﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XNA_TD
{
    public abstract class GroundUnit : Unit
    {
        protected Vector2 targetPos;
        protected float yaw = MathHelper.PiOver2, yawSpeed = 0.01f;

        public GroundUnit(string unit, Vector3 pos)
            : base(unit, pos, GegnerTyp.Boden)
        {
            
        }

        public override void FixedGameUpdate()
        {
            if (pfad.hasNext(position))
            {
                targetPos = pfad.getNext(position);
            }

            Vector3 v = (position - new Vector3(targetPos.X, position.Y, targetPos.Y));
            if (v.Length() <= .5)
            {
                if ((int)targetPos.X == (int)baseTower.position.X &&
                    (int)targetPos.Y == (int)baseTower.position.Z)
                {
                    UnRegister(this);
                    baseTower.Damage(lvlInfo.attackDmg);
                    return;
                }
                else
                {
                    targetPos.X = baseTower.position.X;
                    targetPos.Y = baseTower.position.Z;
                }
            }
            v.Normalize();
            float newYaw = NormalizeAngle(Math.Atan2(v.X, v.Z));
            yaw = NormalizeAngle(Rotate(yaw, newYaw, yawSpeed));

            position.X -= (float)(Math.Sin(yaw) * speed);
            position.Z -= (float)(Math.Cos(yaw) * speed);
            /*if (!pfad.has(position) && (int)targetPos.X == (int)baseTower.position.X && (int)targetPos.Y == (int)baseTower.position.Z)
            {
                position.X += (float)(Math.Sin(yaw) * speed);
                position.Z += (float)(Math.Cos(yaw) * speed);
            }*/
            position.Y = terrain.GetRealHeight(position.X, position.Z);
            rotation = Matrix.CreateRotationY(yaw);
            rotation.Up = terrain.GetNormal(position.X, position.Z);

            rotation.Right = Vector3.Cross(rotation.Forward, rotation.Up);
            rotation.Right = Vector3.Normalize(rotation.Right);

            rotation.Forward = Vector3.Cross(rotation.Up, rotation.Right);
            rotation.Forward = Vector3.Normalize(rotation.Forward);
        }
    }
}
